import { prisma } from '../db/prisma';
import { createSuccessResponse, createErrorResponse } from '../utils/response';
import { z } from 'zod';
import { getVisitRequirement, isVisitRequirementMet } from '../constants/visitRequirements';

export class WorkLogService {
  /**
   * 创建工作日志记录
   */
  static async createWorkLog(input: {
    managerId: number;
    clientId: number;
    serviceId: number;
    completionDate: string;
    notes?: string;
  }) {
    try {
      // 检查是否已存在相同的记录
      const existingLog = await prisma.workLog.findFirst({
        where: {
          managerId: input.managerId,
          clientId: input.clientId,
          serviceId: input.serviceId,
          completionDate: new Date(input.completionDate),
        },
      });

      if (existingLog) {
        return createErrorResponse('该客户在此日期的此项服务已有记录');
      }

      const workLog = await prisma.workLog.create({
        data: {
          managerId: input.managerId,
          clientId: input.clientId,
          serviceId: input.serviceId,
          completionDate: new Date(input.completionDate),
          notes: input.notes,
        },
        include: {
          client: true,
          service: true,
        },
      });

      return createSuccessResponse(workLog, '工作日志创建成功');
    } catch (error) {
      console.error('创建工作日志失败:', error);
      return createErrorResponse('创建工作日志失败');
    }
  }

  /**
   * 获取客户经理的工作日志列表
   */
  static async getWorkLogs(input: {
    managerId: number;
    startDate?: string;
    endDate?: string;
    serviceId?: number;
    page?: number;
    pageSize?: number;
  }) {
    try {
      const page = input.page || 1;
      const pageSize = Math.min(input.pageSize || 20, 100);
      const skip = (page - 1) * pageSize;

      const where: any = {
        managerId: input.managerId,
      };

      if (input.startDate || input.endDate) {
        where.completionDate = {};
        if (input.startDate) {
          where.completionDate.gte = new Date(input.startDate);
        }
        if (input.endDate) {
          where.completionDate.lte = new Date(input.endDate);
        }
      }

      if (input.serviceId) {
        where.serviceId = input.serviceId;
      }

      const [workLogs, total] = await Promise.all([
        prisma.workLog.findMany({
          where,
          include: {
            client: true,
            service: true,
          },
          orderBy: {
            completionDate: 'desc',
          },
          skip,
          take: pageSize,
        }),
        prisma.workLog.count({ where }),
      ]);

      return createSuccessResponse({
        data: workLogs,
        pagination: {
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize),
        },
      }, '获取工作日志成功');
    } catch (error) {
      console.error('获取工作日志失败:', error);
      return createErrorResponse('获取工作日志失败');
    }
  }

  /**
   * 获取指定日期的工作日志
   */
  static async getWorkLogsByDate(input: {
    managerId: number;
    date: string;
  }) {
    try {
      const targetDate = new Date(input.date);
      const workLogs = await prisma.workLog.findMany({
        where: {
          managerId: input.managerId,
          completionDate: targetDate,
        },
        include: {
          client: true,
          service: true,
        },
        orderBy: {
          createdAt: 'desc',
        },
      });

      return createSuccessResponse(workLogs, '获取日期工作日志成功');
    } catch (error) {
      console.error('获取日期工作日志失败:', error);
      return createErrorResponse('获取日期工作日志失败');
    }
  }

  /**
   * 删除工作日志记录
   */
  static async deleteWorkLog(input: { id: string; managerId: number }) {
    try {
      const workLog = await prisma.workLog.findFirst({
        where: {
          id: BigInt(input.id),
          managerId: input.managerId,
        },
      });

      if (!workLog) {
        return createErrorResponse('工作日志不存在或无权限删除');
      }

      await prisma.workLog.delete({
        where: {
          id: BigInt(input.id),
        },
      });

      return createSuccessResponse(null, '删除工作日志成功');
    } catch (error) {
      console.error('删除工作日志失败:', error);
      return createErrorResponse('删除工作日志失败');
    }
  }

  /**
   * 获取客户经理的服务完成统计
   */
  static async getServiceStats(input: {
    managerId: number;
    serviceId: number;
    startDate?: string;
    endDate?: string;
  }) {
    try {
      // 获取客户经理负责的所有客户
      const managerClients = await prisma.managerClientAssignment.findMany({
        where: { managerId: input.managerId },
        include: {
          client: {
            include: {
              serviceAssignments: {
                where: { serviceId: input.serviceId },
              },
            },
          },
        },
      });

      // 筛选出需要提供此服务的客户
      const clientsWithService = managerClients
        .filter(assignment => assignment.client.serviceAssignments.length > 0)
        .map(assignment => assignment.client);

      const totalClients = clientsWithService.length;

      // 获取完成记录
      const where: any = {
        managerId: input.managerId,
        serviceId: input.serviceId,
      };

      if (input.startDate || input.endDate) {
        where.completionDate = {};
        if (input.startDate) {
          where.completionDate.gte = new Date(input.startDate);
        }
        if (input.endDate) {
          where.completionDate.lte = new Date(input.endDate);
        }
      }

      const completedLogs = await prisma.workLog.findMany({
        where,
        include: {
          client: true,
        },
        orderBy: {
          completionDate: 'desc',
        },
      });

      // 按客户分组统计拜访次数
      const visitCountByClient = new Map<number, number>();
      completedLogs.forEach(log => {
        const current = visitCountByClient.get(log.clientId) || 0;
        visitCountByClient.set(log.clientId, current + 1);
      });

      // 根据终端类型和拜访次数判断完成状态
      const completedClients: any[] = [];
      const uncompletedClients: any[] = [];
      let totalRequiredVisits = 0;
      let completedVisits = 0;

      clientsWithService.forEach(client => {
        const actualVisitCount = visitCountByClient.get(client.id) || 0;
        const requiredVisitCount = getVisitRequirement(client.terminalType);
        totalRequiredVisits += requiredVisitCount;
        
        if (isVisitRequirementMet(client.terminalType, actualVisitCount)) {
          completedClients.push({
            ...client,
            actualVisitCount,
            requiredVisitCount
          });
          completedVisits += Math.min(actualVisitCount, requiredVisitCount); // 只计算达到要求的部分
        } else {
          uncompletedClients.push({
            ...client,
            actualVisitCount,
            requiredVisitCount,
            remainingVisits: requiredVisitCount - actualVisitCount
          });
        }
      });

      return createSuccessResponse({
        totalClients,
        completedCount: completedClients.length, // 已完成要求的客户数量
        uncompletedCount: uncompletedClients.length, // 未完成要求的客户数量
        targetCount: totalClients, // 目标客户数量
        totalRequiredVisits, // 总共需要的拜访次数
        actualTotalVisits: completedLogs.length, // 实际总拜访次数
        completedVisits, // 有效完成的拜访次数
        completedClients,
        uncompletedClients,
        recentLogs: completedLogs.slice(0, 10), // 最近10条记录
        // 保持向后兼容
        uniqueCompletedCount: completedClients.length,
      }, '获取服务统计成功');
    } catch (error) {
      console.error('获取服务统计失败:', error);
      return createErrorResponse('获取服务统计失败');
    }
  }

  /**
   * 搜索客户经理的客户
   */
  static async searchClients(input: {
    managerId: number;
    keyword: string;
    serviceId?: number;
  }) {
    try {
      const managerClients = await prisma.managerClientAssignment.findMany({
        where: { managerId: input.managerId },
        include: {
          client: {
            include: {
              serviceAssignments: input.serviceId ? {
                where: { serviceId: input.serviceId },
              } : true,
            },
          },
        },
      });

      let clients = managerClients.map(assignment => assignment.client);

      // 如果指定了服务ID，只返回需要提供该服务的客户
      if (input.serviceId) {
        clients = clients.filter(client => 
          client.serviceAssignments.some(sa => sa.serviceId === input.serviceId)
        );
      }

      // 根据关键词搜索
      const filteredClients = clients.filter(client =>
        client.clientCode.includes(input.keyword) ||
        client.clientName.includes(input.keyword)
      );

      return createSuccessResponse(filteredClients, '搜索客户成功');
    } catch (error) {
      console.error('搜索客户失败:', error);
      return createErrorResponse('搜索客户失败');
    }
  }
}
